package org.hades.corelib.view

import android.view.View
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager


// 一些扩展方法
fun DialogFragment.doShow(
    fm: FragmentManager
) {
    val name = this.javaClass.name
    this.doShow(name, fm)
}

fun DialogFragment.doShow(
    name: String,
    fm: FragmentManager
) {
    val fgByTag = fm.findFragmentByTag(name)
    fgByTag?.let {
        fm.beginTransaction().remove(fgByTag).commitNowAllowingStateLoss()
    }
    if (!this.isAdded
    ) {
        val ft = fm.beginTransaction()
        ft.add(this, name)
        ft.commitNowAllowingStateLoss()
    }

}

fun Fragment.doReplace(
    resId: Int,
    fm: FragmentManager,
    sharedElements: ArrayList<Pair<View, String>>?
) {
    this.doReplace(resId, fm, false, sharedElements)
}

fun Fragment.doReplace(
    resId: Int,
    fm: FragmentManager,
    addToBackStack: Boolean,
    sharedElements: ArrayList<Pair<View, String>>? // 多参数
) {
    val ft = fm.beginTransaction()
    sharedElements?.let {
        for (par in sharedElements) {
            ft.addSharedElement(par.first, par.second)
        }
    }

    val fgTag = fm.findFragmentByTag(this.javaClass.name)
    fgTag?.let {
        fm.popBackStack()
    }

    ft.replace(resId, this, this.javaClass.name)
    if (addToBackStack){
        ft.addToBackStack(null)
    }
    ft.commitNowAllowingStateLoss()

}